/**
 * 
 */
package com.agilegroup.crm.ui;

import static com.agilegroup.crm.utils.CONSTANTS.ADD_ACCOUNT_GET;
import static com.agilegroup.crm.utils.CONSTANTS.ADD_ACCOUNT_POST;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import roboguice.inject.InjectView;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.agilegroup.crm.AgileApplication;
import com.agilegroup.crm.R;
import com.agilegroup.crm.adapters.SpinnerAdapter;
import com.agilegroup.crm.model.Account;
import com.agilegroup.crm.model.City;
import com.agilegroup.crm.model.Country;
import com.agilegroup.crm.model.LeadDetails;
import com.agilegroup.crm.requests.GenericJsonRequest;
import com.agilegroup.crm.requests.PostAccountJsonRequest;
import com.agilegroup.crm.ui.fragments.ConnectionDialogFragment;
import com.agilegroup.crm.utils.OnlineChecker;
import com.agilegroup.crm.utils.SessionManager;
import com.agilegroup.crm.utils.Validation;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.CacheLoadingException;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;

/**
 * @author Hisham
 *
 */
public class NewAccountActivity extends BaseActivity {

	@InjectView(R.id.spinnerCity)
	Spinner spinnerCity;
	
	@InjectView(R.id.spinnerCountry)
	Spinner spinnerCountry;
	
	@InjectView(R.id.lblAccountOwner)
	TextView lblAccountOwner;
	
	@InjectView(R.id.txtAccountName)
	EditText txtAccountName;
	
	@InjectView(R.id.txtCompany)
	EditText txtCompany;
	
	@InjectView(R.id.txtPhone)
	EditText txtPhone;
	
	@InjectView(R.id.txtMobile)
	EditText txtMobile;
	
	@InjectView(R.id.txtFax)
	EditText txtFax;
	
	@InjectView(R.id.txtEmail)
	EditText txtEmail;
	
	@InjectView(R.id.txtArea)
	EditText txtArea;
	
	@InjectView(R.id.txtStreet)
	EditText txtStreet;
	
	@InjectView(R.id.txtZipCode)
	EditText txtZipCode;
	
	@InjectView(R.id.txtWebsite)
	EditText txtWebsite;
	
	@InjectView(R.id.txtAnnualRevenue)
	EditText txtAnnualRevenue;
	
	@InjectView(R.id.txtDescription)
	EditText txtDescription;
	
	@InjectView(R.id.txtEmpNum)
	EditText txtEmpNum;
	
	@InjectView(R.id.spinnerType)
	Spinner spinnerType;
	
	@InjectView(R.id.spinnerIndustry)
	Spinner spinnerIndustry;
	
	private SessionManager sessionManager;
	private static final String JSON_CACHE_KEY = "new_account_get_json";
	
	@SuppressWarnings("static-access")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_account);

		sessionManager = new SessionManager(getBaseContext());    
    	HashMap<String, String> user = sessionManager.getUserDetails();
    	String empId = user.get(sessionManager.KEY_ID);
    	
    	AgileApplication.getInstance().spiceManager.execute(new GenericJsonRequest<LeadDetails>(LeadDetails.class, empId, ADD_ACCOUNT_GET),JSON_CACHE_KEY,
    									DurationInMillis.ALWAYS_EXPIRED,new AccountDetailsListJsonRequestListener());
    	
    	spinnerCountry.setOnItemSelectedListener(selectedListener());
	}
	
	private OnItemSelectedListener selectedListener(){
		OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long id) {
				LeadDetails leadDetails;
				try {
					leadDetails = AgileApplication.getInstance().spiceManager.getDataFromCache(LeadDetails.class, JSON_CACHE_KEY).get();
					Country country = leadDetails.getCountries().get(position);
					resetCity(country);
				} catch (CacheLoadingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ExecutionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {				
			}
		};
		return itemSelectedListener;
	}
	private void resetCity(Country country){      
		List<com.agilegroup.crm.model.Spinner>citiesSpinner = new ArrayList<com.agilegroup.crm.model.Spinner>();
			Set<City>cities = country.getCities();
			if(cities.size()!=0){
				for (City city : cities) {
					com.agilegroup.crm.model.Spinner countrySpinner = new com.agilegroup.crm.model.Spinner();
					countrySpinner.setId(city.getId().toString());
					countrySpinner.setName(city.getName());
					citiesSpinner.add(countrySpinner);
				}
				addItemsToCities(citiesSpinner);
			}
			else{
				com.agilegroup.crm.model.Spinner countrySpinner = new com.agilegroup.crm.model.Spinner();
				countrySpinner.setId("0");
				countrySpinner.setName("--none--");
				citiesSpinner.add(countrySpinner);
				addItemsToCities(citiesSpinner);
			}			
	}
	
	public void addItemsToCities(List<com.agilegroup.crm.model.Spinner>cities){
		SpinnerAdapter adapter = new SpinnerAdapter(NewAccountActivity.this, R.layout.spinner_row, cities);
		spinnerCity.setAdapter(adapter);
	}
	
	private class AccountDetailsListJsonRequestListener implements RequestListener<LeadDetails>{

		@Override
		public void onRequestFailure(SpiceException arg0) {
			Toast.makeText(NewAccountActivity.this, "Failure", Toast.LENGTH_SHORT).show();
			
		}

		@Override
		public void onRequestSuccess(final LeadDetails leadDetails) {
			lblAccountOwner.setText(leadDetails.getOwnerName());
			List<Country>countries=leadDetails.getCountries();
			List<com.agilegroup.crm.model.Spinner>countriesSpinner = new ArrayList<com.agilegroup.crm.model.Spinner>();
			for (Country country : countries) {
				com.agilegroup.crm.model.Spinner countrySpinner = new com.agilegroup.crm.model.Spinner();
				countrySpinner.setId(country.getId().toString());
				countrySpinner.setName(country.getCountryName());
				countriesSpinner.add(countrySpinner);
			}
			addItemsToCountries(countriesSpinner);
		}
		public void addItemsToCountries(List<com.agilegroup.crm.model.Spinner>countries){
			SpinnerAdapter adapter = new SpinnerAdapter(NewAccountActivity.this, R.layout.spinner_row, countries);
			spinnerCountry.setAdapter(adapter);
		}
	}
	@SuppressWarnings("static-access")
	public void addLead(View v){
		List<String> list = new ArrayList<String>();
		StringBuilder builder = new StringBuilder();
		Validation validation = new Validation(this);
		boolean isCompanyNull = validation.isTextFieldNull(txtCompany,R.string.message_comapny_name_requried);
		boolean isEmailValid=true;
		boolean isWebSiteValid=true;
		if(isCompanyNull==false){
			String email = txtEmail.getText().toString();
			String website = txtWebsite.getText().toString();
			if(isCompanyNull==false){
				list.add(getResources().getString(R.string.message_comapny_name_requried));
			}
			if(email!=null&&!email.equalsIgnoreCase("")){
				    isEmailValid = validation.isEmailValid(txtEmail);
				   if(isEmailValid==false){
					   list.add(getResources().getString(R.string.message_email_pattern_error));
				   }
			}
			if(website!=null&&!website.equalsIgnoreCase("")){
			    isWebSiteValid = validation.isWebSiteValid(txtWebsite);
			   if(isWebSiteValid==false){
				   list.add(getResources().getString(R.string.message_website_pattern_error));
				}
		   }
			for(String i : list)
			{
			     builder.append(i + "\n");
			}
			Toast.makeText(this, builder, Toast.LENGTH_LONG).show();
		}
		else{
			List<String> errorList = new ArrayList<String>();
			StringBuilder errorBuilder = new StringBuilder();
			String accountName = txtAccountName.getText().toString();
			String company = txtCompany.getText().toString();
			String fax = txtFax.getText().toString();
			String phone = txtPhone.getText().toString();
			String mobile = txtMobile.getText().toString();
			String email = txtEmail.getText().toString();
			String street = txtStreet.getText().toString();
			String area = txtArea.getText().toString();
			String zipCode = txtZipCode.getText().toString();
			String website = txtWebsite.getText().toString();
			String empNum = txtEmpNum.getText().toString();
			String annualRevenue = txtAnnualRevenue.getText().toString();
			String description = txtDescription.getText().toString();
			
			String type = String.valueOf(spinnerType.getSelectedItem());
			String industry = String.valueOf(spinnerIndustry.getSelectedItem());
			com.agilegroup.crm.model.Spinner country;
    		com.agilegroup.crm.model.Spinner city;
    		
    		HashMap<String, String> user = sessionManager.getUserDetails();
        	String empId = user.get(sessionManager.KEY_ID);
			Account lead = new Account();
        	//Lead lead = new Lead();
			
			lead.setAccountCreatorId(Integer.parseInt(empId));
			if(!(spinnerCountry.getSelectedItem()== null)){
				country = (com.agilegroup.crm.model.Spinner)spinnerCountry.getSelectedItem();
				lead.setCountryId(Integer.parseInt(country.getId()));
           }
			if(!(spinnerCity.getSelectedItem()== null)){
				city = (com.agilegroup.crm.model.Spinner)spinnerCity.getSelectedItem();
				lead.setCityId(Integer.parseInt(city.getId()));
           }
		   if(accountName!=null&&!accountName.equalsIgnoreCase("")){
			   lead.setAccountName(accountName);
		   }
		   if(company!=null&&!company.equalsIgnoreCase("")){
			   lead.setCompanyName(company);
		   }
		   if(fax!=null&&!fax.equalsIgnoreCase("")){
			   lead.setFax(fax);
		   }
		   if(phone!=null&&!phone.equalsIgnoreCase("")){
			   lead.setPhone(phone);
		   }
		   if(mobile!=null&&!mobile.equalsIgnoreCase("")){
			   lead.setMobile(mobile);
		   }
		   if(email!=null&&!email.equalsIgnoreCase("")){
			    isEmailValid = validation.isEmailValid(txtEmail);
			   if(isEmailValid==true){
				   lead.setEmail(email);
				//   sucess=true;
			   }
			   else{
				 //  sucess=false;
				   errorList.add(getResources().getString(R.string.message_email_pattern_error));
			   }  
		   }
		   if(street!=null&&!street.equalsIgnoreCase("")){
			   lead.setStreet(street);
		   }
		   if(area!=null&&!area.equalsIgnoreCase("")){
			   lead.setState(area);
		   }
		   if(zipCode!=null&&!zipCode.equalsIgnoreCase("")){
			   lead.setZipCode(zipCode);
		   }
		   if(website!=null&&!website.equalsIgnoreCase("")){
			    isWebSiteValid = validation.isWebSiteValid(txtWebsite);
			   if(isWebSiteValid==true){
				   lead.setWebSite(website); 
			   }
			   else{
				   errorList.add(getResources().getString(R.string.message_website_pattern_error));
			   }
		   }

		   if(empNum!=null&&!empNum.equalsIgnoreCase("")){
			   lead.setEmpNum(Integer.parseInt(empNum));
		   }
		   if(annualRevenue!=null&&!annualRevenue.equalsIgnoreCase("")){
			   lead.setAnnualRevenue(Integer.parseInt(annualRevenue));
		   }
		   if(description!=null&&!description.equalsIgnoreCase("")){
			   lead.setDescription(description);
		   }
		   if(type!=null&&!type.equalsIgnoreCase("")){
			   lead.setType(type);
		   }
		   if(industry!=null&&!industry.equalsIgnoreCase("")){
			   lead.setIndustry(industry);
		   }
		   lead.setIsDeleted(false);
		   lead.setDateCreated(new Date());
		   if(isWebSiteValid!=true||isEmailValid!=true){
			   for(String i : errorList)
				{
				   errorBuilder.append(i + "\n");
				}
			   Toast.makeText(this, errorBuilder, Toast.LENGTH_SHORT).show();
		   }
		   else{
			   OnlineChecker checker = new OnlineChecker(NewAccountActivity.this);
			   if(checker.isOnline()==true){
				   postNewAccount(lead); 
			   }
			   else{
				   SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
       			   dialogFragment.show(getSupportFragmentManager(), "connectionDialog");
			   }
		   }
		}
	}
	public void postNewAccount(Account account){
		AgileApplication.getInstance().spiceManager.execute(new PostAccountJsonRequest(account,ADD_ACCOUNT_POST), new newAccountJsonRequestListener());
	}
	public class newAccountJsonRequestListener implements RequestListener<Account>{

		@Override
		public void onRequestFailure(SpiceException spiceException) {
			Toast.makeText(NewAccountActivity.this, "Failure", Toast.LENGTH_SHORT).show();
			
		}

		@Override
		public void onRequestSuccess(Account result) {
			Toast.makeText(NewAccountActivity.this, "Sucess", Toast.LENGTH_SHORT).show();
			finish();
			
		}
		
	}
	public void cancelButton(View v){
		finish();
	}
}